﻿Imports System.ServiceModel.DomainServices.Client
Imports LullabyFullDeCaixa.Web
Imports System.Collections.ObjectModel

Partial Public Class DetallGestioThingsToDo
    Inherits ChildWindow

#Region "Crear i Destruir"
    Public Sub New()
        InitializeComponent()
    End Sub

    Private Sub Child_Closed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Closed
        Application.Current.RootVisual.SetValue(Control.IsEnabledProperty, True)
    End Sub

    Private Sub DetallGestioHostals_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        If RiaContext.Current.Authentication.User.Identity.IsAuthenticated = True Then
            Me.Activity.IsActive = True

            AddHandler Contexte.HostalsCarregats, AddressOf HostalsCarregats
            Contexte.LoadHostals()
            AddHandler Contexte.UsuarisCarregats, AddressOf UsuarisCarregats
            Contexte.LoadUsuaris()
            AddHandler Contexte.CategoriesCarregades, AddressOf CategoriesCarregades
            Contexte.LoadCategories()

            Me.grdElements.ItemsSource = DadesBuscador
        End If
    End Sub
#End Region

#Region "Guardar i Cancelar"
    Private Sub OKButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        EliminarObjectErrors()

        If LullabyFullDeCaixa.Contexte.DomainContext.EntityContainer.HasChanges Then
            If ValidarDades() Then
                LullabyFullDeCaixa.Contexte.DomainContext.SubmitChanges(AddressOf DomainContext_SubmittedChanges, Nothing)
                Activity.IsActive = True
            End If
        Else
            Me.DialogResult = True
        End If
    End Sub

    Private Function ValidarDades() As Boolean
        Dim Resultat As Boolean = True

        Return Resultat
    End Function

    Private Sub DomainContext_SubmittedChanges(ByVal s As SubmitOperation)
        Activity.IsActive = False

        If s.HasError Then
            App.ReportError(StringLibrary.ErrorGuardantDades)
        Else
            Me.DialogResult = True
        End If
    End Sub

    Private Sub CancelButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
        If LullabyFullDeCaixa.Contexte.DomainContext.EntityContainer.HasChanges Then
            LullabyFullDeCaixa.Contexte.DomainContext.RejectChanges()
        End If

        Me.DialogResult = False
    End Sub

    Public Sub EliminarObjectErrors()
        Dim i As Long

        i = 0
        While i < Validacio.Errors.Count
            If Validacio.Errors(i).ItemType = ValidationSummaryItemType.ObjectError Then
                Validacio.Errors.RemoveAt(i)
            Else
                i = i + 1
            End If
        End While
    End Sub
#End Region

#Region "Carregar Dades"
    Private _HostalsCarregats As Boolean = False
    Private _UsuarisCarregats As Boolean = False
    Private _CategoriesCarregades As Boolean = False

    Public Sub HostalsCarregats(ByVal Resultat As Boolean, ByVal Missatge As String)
        RemoveHandler Contexte.HostalsCarregats, AddressOf HostalsCarregats
        _HostalsCarregats = True

        If _HostalsCarregats And _UsuarisCarregats And _CategoriesCarregades Then
            Me.Activity.IsActive = False
            OmpleDadesBuscador()
        End If
    End Sub

    Public Sub UsuarisCarregats(ByVal Resultat As Boolean, ByVal Missatge As String)
        RemoveHandler Contexte.UsuarisCarregats, AddressOf UsuarisCarregats
        _UsuarisCarregats = True

        If _HostalsCarregats And _UsuarisCarregats And _CategoriesCarregades Then
            Me.Activity.IsActive = False
            OmpleDadesBuscador()
        End If
    End Sub

    Public Sub CategoriesCarregades(ByVal Resultat As Boolean, ByVal Missatge As String)
        RemoveHandler Contexte.CategoriesCarregades, AddressOf CategoriesCarregades
        _CategoriesCarregades = True

        If _HostalsCarregats And _UsuarisCarregats And _CategoriesCarregades Then
            Me.Activity.IsActive = False
            OmpleDadesBuscador()
        End If
    End Sub
#End Region

#Region "Buscador"

    Private DadesBuscador As ObservableCollection(Of ThingToDo) = New ObservableCollection(Of ThingToDo)

    Private Sub Buscador_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        BuscaThingsToDo(True)
    End Sub

    Private Sub OmpleDadesBuscador()
        If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador Then
            Dim LListaHostals As List(Of Hostal) = Contexte.Hostals.ToList
            LListaHostals.Insert(0, New Hostal() With {.Id = -1, .Nom = ""})
            Me.cboHostals.ItemsSource = LListaHostals
        Else
            Me.cboHostals.ItemsSource = Contexte.HostalsPerUsuariActual
        End If

        Me.cboHostals.SelectedItem = cboHostals.Items(0)

        Dim Categories As List(Of ThingsToDoCategory) = (From c As ThingsToDoCategory In Contexte.Categories Where c.EsBaixa = False).ToList
        Categories.Insert(0, New ThingsToDoCategory() With {.Id = -1, .Nom = " "})
        Me.cboCategories.ItemsSource = Categories
        Me.cboCategories.SelectedItem = cboCategories.Items(0)

        Dim Urgencies As List(Of Urgencia) = Contexte.Urgencies
        Urgencies.Insert(0, New Urgencia(EnumUrgencia.Indefinida))
        Me.cboUrgencies.ItemsSource = Urgencies
        Me.cboUrgencies.SelectedItem = cboUrgencies.Items(0)

        Me.cboEstat.ItemsSource = OpcionsComboSiNo.Llista
        Me.cboEstat.SelectedItem = cboEstat.Items(2)

        BuscaThingsToDo(True)
    End Sub

    Private Sub BuscaThingsToDo(MostrarBarraProgrés As Boolean)
        Me.Activity.IsActive = MostrarBarraProgrés

        'DirectCast(Me.cboHostals.SelectedItem, Hostal).Id, DataInicial, DataFinal), _
        LullabyFullDeCaixa.Contexte.DomainContext.Load(LullabyFullDeCaixa.Contexte.DomainContext.GetThingsToDoByHostalCategoriaUrgenciaEstatQuery(DirectCast(Me.cboHostals.SelectedItem, Hostal).Id, DirectCast(Me.cboCategories.SelectedItem, ThingsToDoCategory).Id, DirectCast(Me.cboUrgencies.SelectedItem, Urgencia).Id, DirectCast(Me.cboEstat.SelectedItem, OpcioCombo).Id), _
           New Action(Of LoadOperation(Of LullabyFullDeCaixa.Web.ThingToDo))(AddressOf ThingsToDoLoaded), _
           Nothing)
    End Sub

    Private Sub ThingsToDoLoaded(ByVal ThingToDo As LoadOperation(Of LullabyFullDeCaixa.Web.ThingToDo))
        'Un cop carregat ho guardem en una llista
        Me.Activity.IsActive = False

        DadesBuscador.Clear()

        'Afegim els nous
        For Each Thing As ThingToDo In (From D As ThingToDo In ThingToDo.Entities Order By D.Id).ToList()
            If Not DadesBuscador.Contains(Thing) Then DadesBuscador.Insert(0, Thing)
        Next

        ''Traiem els vells
        'Dim ThingsATreure As List(Of ThingToDo) = New List(Of ThingToDo)
        'For Each Thing As ThingToDo In DadesBuscador
        '    If Not ThingToDo.Entities.Contains(Thing) Then ThingsATreure.Add(Thing)
        'Next

        'For Each Thing As ThingToDo In ThingsATreure
        '    DadesBuscador.Remove(Thing)
        'Next

    End Sub
#End Region

#Region "Boto Eliminar i afegir"

    Private Sub btnEliminar_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim Thing As ThingToDo = DirectCast(grdElements.SelectedItem, ThingToDo)

        LullabyFullDeCaixa.Contexte.DomainContext.ThingToDos.Remove(Thing)

        DadesBuscador.Remove(Thing)
    End Sub

    Private Sub btnAfegir_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        Dim nouThingToDo As New LullabyFullDeCaixa.Web.ThingToDo() With {.IdUsuari = Contexte.UsuariActual.Id, .Realizada = False, .Data = Now, .Urgencia = EnumUrgencia.Normal, .IdCategoria = -1}
        Contexte.DomainContext.ThingToDos.Add(nouThingToDo)


        Dim Child As ThingsToDoAltaModificacio = New ThingsToDoAltaModificacio(ThingsToDoAltaModificacio.EnumMode.ModeAlta, nouThingToDo)
        AddHandler Child.Closed, AddressOf Child_Tancat

        Child.Show()
    End Sub

    Private Sub btnEditar_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
        Dim ThingToDo As ThingToDo = grdElements.SelectedItem

        Dim Child As ThingsToDoAltaModificacio = New ThingsToDoAltaModificacio(ThingsToDoAltaModificacio.EnumMode.ModeModificacio, ThingToDo)
        AddHandler Child.Closed, AddressOf Child_Tancat
        Child.Show()
    End Sub

    Private Sub Child_Tancat(Sender As Object, e As System.EventArgs)
        Dim Child As ThingsToDoAltaModificacio = DirectCast(Sender, ThingsToDoAltaModificacio)
        RemoveHandler Child.Closed, AddressOf Child_Closed

        If Child.DialogResult And Child.Mode = ThingsToDoAltaModificacio.EnumMode.ModeAlta Then
            DadesBuscador.Insert(0, Child.ThingToDo)
            grdElements.SelectedItem = Child.ThingToDo
        End If
    End Sub
#End Region

    Private Sub grdElements_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles grdElements.SelectionChanged
        If e.AddedItems.Count = 0 Then
            Me.gridDetall.Visibility = Windows.Visibility.Collapsed
            Me.btnEliminar.IsEnabled = False
            Me.btnEditar.IsEnabled = False
        Else
            Dim ThingToDo As ThingToDo = DirectCast(e.AddedItems(0), ThingToDo)

            Me.gridDetall.Visibility = Windows.Visibility.Visible
            If Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Administrador OrElse Contexte.UsuariActual.IdTipusUsuari = EnumTipusUsuari.Manager OrElse Contexte.UsuariActual Is ThingToDo.Usuari Then
                Me.btnEliminar.IsEnabled = True
                Me.btnEditar.IsEnabled = True
            Else
                Me.btnEliminar.IsEnabled = False
                Me.btnEditar.IsEnabled = False
            End If
        End If
    End Sub

    Private Sub Scroll_SizeChanged(ByVal sender As System.Object, ByVal e As System.Windows.SizeChangedEventArgs)
        Me.Components.MaxHeight = Math.Max(Me.Scroll.ViewportHeight, Me.Components.MinHeight)
        Me.Components.MaxWidth = Math.Max(Me.Scroll.ViewportWidth, Me.Components.MinWidth)
    End Sub

End Class

